//
//  AuthViewController.swift
//  Weibo
//
//  Created by 唐润欣 on 16/6/18.
//  Copyright © 2016年 唐润欣. All rights reserved.
//

import UIKit

//MARK: - 属性、构造函数、生命周期函数
class AuthViewController: UIViewController {

    lazy var webView = UIWebView()
    
    //导航条左边的注册按钮
    lazy var cancleBarButtonItem: UIBarButtonItem = UIBarButtonItem(title: "取消", style: .Plain, target: self, action: "cancle")
    
    override func loadView() {
        
        view = webView
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
//        view.backgroundColor = UIColor.whiteColor()
        
        setupUI()
        loadWebView()
    }
}

// MARK: - 设置UI
extension AuthViewController {
    
    func setupUI() {
        
        view.backgroundColor = UIColor.whiteColor()
        self.navigationItem.leftBarButtonItem = cancleBarButtonItem
    }
}

// MARK: - 加载页面
extension AuthViewController {
    
    ///  加载用户登录页面
    func loadWebView() {
        
        let url = NSURL(string: NetworkTool.sharedTool.oauthURLString)
        let request = NSURLRequest(URL: url!)
        
        webView.loadRequest(request)
    }
}

// MARK: - UIWebview的代理方法
extension AuthViewController: UIWebViewDelegate {
    
    ///  webView将要加载urlRequest时调用
    ///
    ///  - parameter webView:        当前的webView
    ///  - parameter request:        将要请求的request
    ///  - parameter navigationType: 暂时用不上
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
//        print("\(request.URL?.absoluteString)\n- - - - - - -")
        
        if let urlString = request.URL?.absoluteString where urlString.hasPrefix(redirectURL) {
            
            //判断是否有code
            //query是url当中的所有的参数和值
//            print(request.URL?.query)
            
            //判断用户点击是授权还是取消：如果参数url中有“code=”，说明用户授权，否则用户取消授权
            if let query = request.URL?.query where query.hasPrefix("code=") {
                
                //rangeOfString 获取子串的range
                let startIndex = query.rangeOfString("code=")?.endIndex
                let code = query.substringFromIndex(startIndex!)
                
                //调用loadAccessToken业务层来获取accesstoken
                NetworkTool.sharedTool.loadAccesstoken(code, callBack: { (response) -> () in
                    
                    //获取授权成功
                    if let accessTokenDic = response {
                        
                        //请求登录帐号信息
                        NetworkTool.sharedTool.loadUserAccount(accessTokenDic["access_token"] as! String, uid: accessTokenDic["uid"] as! String, callBack: { (response) -> () in
                            
                            //所用户信息保存在本地
                                if var userDic = response {
                                    
                                    //将userDic 和 accessTokenDic 合并
                                    for (key, value) in accessTokenDic {
                                        
                                        userDic[key] = value
                                    }
                                    
                                    //合并成功之后，保存用户信息
                                    UserAccount.sharedUserAccount.saveUserAccount(userDic)
                                    
                                    //向展示的页面发送用户授权成功的通知
                                    let authSuscessNotification = NSNotification(name: oauthSuccessNotification, object: nil)
                                    NSNotificationCenter.defaultCenter().postNotification(authSuscessNotification)
                                }
                            })
                    }
                })
            }
            
            //延迟1.2秒 dismiss掉当前的页面
            delay(1.2, clousure: { () -> () in
                
            self.dismissViewControllerAnimated(true, completion: nil)
                
            })
            
            //如果url中包含回调地址，返回false，不加载对应的url的页面。
            return false
            
        } else {
            
            return true
        }
    }
    
    ///  webView加载完成后调用
    ///
    ///  - parameter webView: 当前的webview
    func webViewDidFinishLoad(webView: UIWebView) {
        
        webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = 'sunshinex1n@qq.com';document.getElementById('passwd').value = 'qq8865954'")
    }
}

// MARK: - 页面中点击事件的处理
extension AuthViewController {
    
    //取消授权
    func cancle() {
        
        delay(1.2,clousure: {
            
            //延迟1.2秒 dismiss掉当前的页面
            self.dismissViewControllerAnimated(true, completion: nil)
        })
    }
}
